<template>
  <view class="period-container">
    <!-- 使用uview的导航栏组件 -->
    <up-navbar bgColor="#ff6700" title="营员管理" titleStyle="color: #ffffff; font-size: 36rpx; font-weight: bold"
      :safeAreaInsetTop="true" height="88rpx">
      <template #left>
        <view class="nav-left" @click="goBack">
          <up-icon name="arrow-left" size="24" color="#fff"></up-icon>
          <text class="nav-back-text">返回</text>
        </view>
      </template>
    </up-navbar>
		

    <!-- 营员列表 -->
    <view class="cadet-list">
		
			<!-- 安全距离块 -->
			<view class="safe-area" :style="{ height: (GM_STATUS_BAR_HEIGHT + 80) + 'rpx' }"></view>
		
      <!-- 使用v-for循环渲染营员卡片 -->
      <view class="cadet-card" v-for="(cadet, index) in cadets" :key="cadet.id || index">
        <!-- <view class="cadet-header">
          <view class="age-gender-container">
            <view class="name-tag">{{ cadet.name || '未填写' }}</view>
            <view class="age-tag">{{ cadet.ageRange || '未设置' }}</view>
            <view class="gender-icon" v-if="cadet.gender">
              <up-icon :name="cadet.gender === 'male' ? 'man' : 'woman'"
                :color="cadet.gender === 'male' ? '#1890ff' : '#ff4d4f'" size="24"></up-icon>
            </view>
          </view>
          <view class="cadet-actions">
            <button class="edit-btn" @click="editCadet(cadet.id || index)">编辑</button>
          </view>
        </view>
        <view class="cadet-info">
          <view class="info-item">
            <text class="info-label">身份证号</text>
            <text class="info-value">{{ cadet.idCard || '未填写' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">常住地址</text>
            <text class="info-value">{{ cadet.address || '未填写' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">学校</text>
            <text class="info-value">{{ cadet.school || '未填写' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">校外机构</text>
            <text v-for="item in cadet.institutions" :key="item.institution" class="info-value">{{ item.institution ||
              '未填写'
              }}</text>
          </view>
        </view> -->
				
				<view class="flex-row-start cadet-wrap">
					<view class="cadet-left">
						<image :src="cadet.photo"></image>
						<view class="info-level">Lv.01青铜</view>
					</view>
					<view class="cadet-right flex-1">
						<view class="flex-row-between" style="width: 100%;">
							<view>
								<view class="flex-row-start">
									{{ cadet.name || '未填写' }}
									<view class="info-age" :class="cadet.gender === 'male' ? 'blue' : 'pink'">
										{{ cadet.ageRange || '未设置' }}
									</view>
								</view>
								<view class="u-m-t-10 color-666 u-font-24">{{ cadet.idCard || '未填写' }}</view>
							</view>
							<view class="info-update" @click="editCadet(cadet.id || index)">
								更新
							</view>
						</view>
						<view class="u-font-24 color-999 u-m-t-40">营员备注</view>
						<view class="u-m-t-10">不吃青菜</view>
					</view>
				</view>
      </view>
			
			<view class="cadet-card parent-card">
				<view class="flex-row-between">
					<view class="flex-row-start">
						<view class="u-m-r-30">韩女士</view>
						<view class="info-tag">联系人</view>
						<view class="info-tag">家长</view>
					</view>
					<view class="info-update">
						更新
					</view>
				</view>
				<view class="info-item">
					<text class="info-label">手机号码</text>
					<text class="info-value">188888888888</text>
				</view>
				<view class="info-item">
					<text class="info-label">身份证号</text>
					<text class="info-value">{{ '未填写' }}</text>
				</view>
			</view>

      <!-- 空状态显示 -->
      <view class="empty-state" v-if="cadets.length === 0">
        <text class="empty-text">暂无营员信息</text>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <button class="add-btn goback-btn" @click="goBack" plain>返回</button>
      <button class="add-btn add-cadet-btn" @click="addCadet">添加营员</button>
      <button class="add-btn add-guardian-btn" @click="addGuardian">添加监护人</button>
    </view>
  </view>
</template>

<script>
import { mapState } from 'pinia';
import { useUserStore } from '@/store';
import { request } from '@/utils/request';

export default {
  data() {
    return {
      // 使用数组存储营员列表
      cadets: [],
			GM_STATUS_BAR_HEIGHT: uni.getStorageSync('GM_STATUS_BAR_HEIGHT'),
    };
  },
  computed: {
    ...mapState(useUserStore, ['userInfo'])
  },
  onLoad() {
    // 页面加载时获取营员数据
    // this.fetchCadetData();
  },
  onShow() {
    // 页面显示时获取营员数据
    this.fetchCadetData();
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack({
        delta: 1
      });
    },

    // 根据身份证号判断性别
    getGenderByIdCard(idCard) {
      if (!idCard || idCard.length !== 18) {
        return null;
      }

      // 身份证号第17位（倒数第二位）判断性别，奇数为男，偶数为女
      const genderNum = parseInt(idCard.charAt(16));
      return genderNum % 2 === 1 ? 'male' : 'female';
    },

    // 根据身份证号计算年龄
    getAgeByIdCard(idCard) {
      if (!idCard || idCard.length !== 18) {
        return null;
      }

      // 获取身份证号中的出生年月日（第7-14位）
      const birthYear = parseInt(idCard.substring(6, 10));
      const birthMonth = parseInt(idCard.substring(10, 12));
      const birthDay = parseInt(idCard.substring(12, 14));

      // 获取当前日期
      const now = new Date();
      const currentYear = now.getFullYear();
      const currentMonth = now.getMonth() + 1; // 月份从0开始，需要+1
      const currentDay = now.getDate();

      // 计算年龄
      let age = currentYear - birthYear;

      // 调整年龄：如果当前月份小于出生月份，或者月份相同但日期小于出生日期，则年龄减1
      if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
        age--;
      }

      // 格式化为"X岁+"格式
      return `${age}岁+`;
    },

    // 获取营员数据
    async fetchCadetData() {
      try {
        console.log('获取营员数据');

        // 使用request.js发送GET请求到campers接口
        const response = await request({
          url: '/campers',
          method: 'GET',
          loading: true
        });

        // 假设API返回的数据结构是{ data: [...] }
        const cadetList = response.data || [];

        // 为每个营员添加性别和年龄信息
        this.cadets = cadetList.map(cadet => ({
          ...cadet,
          // 如果已有gender属性则使用，否则根据身份证号判断
          gender: cadet.gender || this.getGenderByIdCard(cadet.idCard),
          // 如果已有ageRange属性则使用，否则根据身份证号计算
          ageRange: cadet.ageRange || this.getAgeByIdCard(cadet.idCard)
        }));
      } catch (error) {
        console.error('获取营员数据失败:', error);
        uni.showToast({
          title: '获取营员数据失败',
          icon: 'none'
        });
      }
    },

    // 编辑营员信息
    editCadet(id) {
      console.log('编辑营员:', id);
      // 跳转到编辑页面，可以传递营员ID
      uni.navigateTo({
        url: `/public/period/editPeriod?id=${id}`
      });
    },

    // 添加营员
    addCadet() {
      console.log('添加营员');
      uni.navigateTo({
        url: '/public/period/editPeriod?mode=add'
      });
    },

    // 添加监护人
    addGuardian() {
      console.log('添加监护人');
      // 可以跳转到监护人添加页面或显示添加监护人的弹窗
      uni.showToast({
        title: '添加监护人功能待实现',
        icon: 'none'
      });
    }
  }
};
</script>

<style scoped lang="scss">
.period-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

/* uview导航栏相关样式 */
.nav-left {
  display: flex;
  align-items: center;
  color: #fff;
}

.nav-back-text {
  color: #fff;
  margin-left: 8rpx;
  font-size: 30rpx;
}

.nav-right {
  display: flex;
  align-items: center;
}

/* 营员列表 */
.cadet-list {
  flex: 1;
  padding: 30rpx 30rpx 200rpx;
  /* margin-top: 120rpx; */
  /* 为导航栏留出空间 */
}

/* 营员卡片 */
.cadet-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.cadet-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.cadet-name {
  font-size: 32rpx;
  font-weight: bold;
}

/* 年龄和性别容器 */
.age-gender-container {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.age-tag {
  background-color: #fff1e6;
  color: #ff6700;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  border: 1rpx solid #ffd5b3;
}

/* 性别图标样式 */
.gender-icon {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-btn {
  background-color: #ff6700;
  color: #fff;
  font-size: 28rpx;
  padding: 0 30rpx;
  height: 68rpx;
  line-height: 68rpx;
  border-radius: 34rpx;
  border: none;
}

.cadet-info {
  width: 100%;
}

.info-item {
  display: flex;
  padding-top: 30rpx;
  align-items: center;
}


.info-label {
  width: 150rpx;
  color: #999;
  font-size: 28rpx;
}

.info-value {
  flex: 1;
  color: #333;
  font-size: 28rpx;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-text {
  font-size: 32rpx;
}

/* 底部操作按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  gap: 30rpx;
	justify-content: space-between;
	font-size: 28rpx;
	padding-bottom: calc(contant(safe-area-inset-bottom) + 0rpx);
	padding-bottom: calc(env(safe-area-inset-bottom) + 0rpx);
}

.add-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
	padding: 0;
}

.add-cadet-btn {
  background-color: #ff6700;
  color: #fff;
}

.add-guardian-btn {
  background-color: #ff6700;
  color: #fff;
}

.goback-btn{
	border: 2rpx solid #ff6700;
	color: #ff6700;
}

/* 适配不同屏幕尺寸 */
@media screen and (min-width: 768px) {
  .period-container {
    max-width: 600rpx;
    margin: 0 auto;
  }
}

.cadet-wrap{
	align-items: flex-start;
	
	.cadet-left{
		margin-right: 30rpx;
			
		image{
			height: 140rpx;
			width: 140rpx;
			border-radius: 20rpx;
		}
		.info-level{
			background: #02A7F0;
			color: #fff;
			font-size: 26rpx;
			text-align: center;
			padding: 4rpx 0;
			border-radius: 4rpx;
			margin-top: 8rpx;
		}
	}
	
	.cadet-right{
		font-size: 28rpx;
		align-items: flex-start;
		height: 100%;
		
		.info-age{
			display: inline-block;
			color: #fff;
			font-size: 24rpx;
			padding: 4rpx 20rpx;
			margin-left: 40rpx;
			border-radius: 10rpx;
			
			&.blue{
				background: #02A7F0;
			}
			&.pink{
				background: #EC808D;
			}
		}
	}
}
.info-update{
	color: #ff6700;
	border: 2rpx solid #ff6700;
	padding: 16rpx 24rpx;
	font-size: 26rpx;
	border-radius: 16rpx;
}
.parent-card{
	background: #fff;
	
	.info-tag{
			display: inline-block;
			color: #fff;
			font-size: 24rpx;
			padding: 4rpx 20rpx;
			margin-left: 20rpx;
			border-radius: 10rpx;
			background: #AAAAAA;
	}
}
</style>